package com.jpyl.jpMedicalTreatment.view.activity.self;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.lordbasewidget.wheelpicker.view.DateTimePicker;
import com.forxindu.kit.box.DateKit;
import com.forxindu.kit.box.VerifyKit;
import com.forxindu.kit.box.ViewKit;
import com.google.gson.JsonObject;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.QueryUserModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.model.event.MineEvent;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.util.StringUtil;
import com.jpyl.jpMedicalTreatment.view.activity.BaseActivity;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 实名认证界面
 * Created by 15697 on 2019/3/7.
 */

public class CertificationActivity extends BaseActivity {

    final RequestApi publicApi = Network.getRequestApi();
    RxSpf_UserModel spfUserModel;
    @BindView(R.id.tv_cer_myDoctor)
    TextView tvCerMyDoctor;
    @BindView(R.id.tv_cer_myName)
    EditText tvCerMyName;
    @BindView(R.id.tv_cer_myBirth)
    TextView tvCerMyBirth;
    @BindView(R.id.tv_cer_myEmail)
    EditText tvCerMyEmail;
    @BindView(R.id.tv_cer_myAddress)
    EditText tvCerMyAddress;
    @BindView(R.id.tv_cer_myIdCard)
    EditText tvCerMyIdCard;
    @BindView(R.id.tv_cer_myIntegral)
    TextView tvCerMyIntegral;
    String doctorId = "", userId = "";
    private DateTimePicker dateTimePicker;
    private String myBirthday;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_certification;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        mTitleTv.setText(getString(R.string.mine_certification));
        spfUserModel = RxSpf_UserModel.create(this);
        userId = spfUserModel.userId().get();
        jpylQueryUserById(spfUserModel.userId().get());
        tvCerMyDoctor.setText(spfUserModel.doctorName().get());
        doctorId = spfUserModel.doctorId().get();
        initPicker();
        dateTimePicker.setOnPositiveButtonClick(new DateTimePicker.OnDateTimePositiveButtonClick() {

            @Override
            public void onReceivedSelectedTime(Calendar selectedTime, String timeText) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onReceivedSelectedDateTime(Calendar selectedDateTime, String dateTimeText) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onReceivedSelectedDate(Calendar selectedDate, String dateText) {
                // TODO Auto-generated method stub
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String dateStr = sdf.format(selectedDate.getTime());
                tvCerMyBirth.setText(dateStr);
                myBirthday = dateStr;
            }
        });
        tvCerMyBirth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dateTimePicker.showPicker(v);
            }
        });
    }

    private void jpylQueryUserById(String userId) {
        publicApi.jpylQueryUserById(userId).map(new Func1<ResponseModel<QueryUserModel>,
                QueryUserModel>() {
            @Override
            public QueryUserModel call(ResponseModel<QueryUserModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<QueryUserModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        }
                    }

                    @Override
                    public void onNext(QueryUserModel model) {
                        myBirthday = model.getUser().getBirthday();
                        tvCerMyName.setText(model.getUser().getUsername());
                        tvCerMyBirth.setText(model.getUser().getBirthday());
                        tvCerMyEmail.setText(model.getUser().getEmail());
                        tvCerMyAddress.setText(model.getUser().getAddress());
                        tvCerMyIdCard.setText(model.getUser().getCid());
                        tvCerMyIntegral.setText(model.getUser().getPoint() + "");
                    }
                });
    }

    @OnClick({R.id.rela_cer_myDoctor, R.id.btn_cer_submit})
    public void Onclick(View view) {
        switch (view.getId()) {
            //选择医生
            case R.id.rela_cer_myDoctor:
                startActivityForResult(new Intent(getApplicationContext(), MyDoctorByPatientActivity
                        .class), 1);
                break;
            //提交按钮
            case R.id.btn_cer_submit:
                if (StringUtil.isEmpty(doctorId)) {
                    ViewKit.showCenterToast(getApplicationContext(), "请选择医生");
                    return;
                }
                if (StringUtil.isEmpty(tvCerMyName.getText().toString())) {
                    tvCerMyName.requestFocus();
                    ViewKit.showCenterToast(getApplicationContext(), "请输入姓名");
                    return;
                }
                if (StringUtil.isEmpty(myBirthday)) {
                    ViewKit.showCenterToast(getApplicationContext(), "请输入出生年月");
                    return;
                }
                if (StringUtil.isEmpty(tvCerMyEmail.getText().toString())) {
                    tvCerMyEmail.requestFocus();
                    ViewKit.showCenterToast(getApplicationContext(), "请输入电子邮箱");
                    return;
                }
                if (StringUtil.isEmpty(tvCerMyAddress.getText().toString())) {
                    tvCerMyAddress.requestFocus();
                    ViewKit.showCenterToast(getApplicationContext(), "请输入地址");
                    return;
                }
                if (StringUtil.isEmpty(tvCerMyIdCard.getText().toString())) {
                    tvCerMyIdCard.requestFocus();
                    ViewKit.showCenterToast(getApplicationContext(), "请输入身份证号码");
                    return;
                }
                if (!VerifyKit.isEmail(tvCerMyEmail.getText().toString().trim())) {
                    tvCerMyEmail.requestFocus();
                    ViewKit.showCenterToast(getApplicationContext(), "请输入正确的邮箱地址");
                    return;
                }
                if (!VerifyKit.isLegalId(tvCerMyIdCard.getText().toString().trim())) {
                    tvCerMyIdCard.requestFocus();
                    ViewKit.showCenterToast(getApplicationContext(), "请输入正确的身份证号码");
                    return;
                }

                jpylEditUser();
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (data != null) {
                doctorId = data.getStringExtra("doctorId");
                tvCerMyDoctor.setText(data.getStringExtra("doctorName"));
            }
        }
    }

    void jpylEditUser() {

        final JsonObject body = new JsonObject();
        JsonObject object = new JsonObject();
        object.addProperty("id", userId);
        object.addProperty("username", tvCerMyName.getText().toString());
        object.addProperty("gender", "");
        object.addProperty("birthday", tvCerMyBirth.getText().toString());
        object.addProperty("nation", "");
        object.addProperty("email", tvCerMyEmail.getText().toString());
        object.addProperty("address", tvCerMyAddress.getText().toString());
        object.addProperty("doctorid", doctorId);
        object.addProperty("cid", tvCerMyIdCard.getText().toString());
        body.addProperty("user", object.toString());

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("user", object.toString());

        publicApi.jpylEditUser(hashMap).map(new Func1<ResponseModel<Object>,
                Object>() {
            @Override
            public Object call(ResponseModel<Object> responseModel) {
                if (responseModel.getCode() != 0) {
                    String msg = responseModel.getMsg();
                    throw new ApiError(responseModel.getCode(), msg);
                }
                return responseModel.getMsg();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(CertificationActivity.this, error.getMsg() + "");
                        }
                    }

                    @Override
                    public void onNext(Object object) {
                        ViewKit.showToast(CertificationActivity.this, "修改信息成功");
                        EventBus.getDefault().post(new MineEvent(tvCerMyName.getText().toString()));
                        finish();
                    }
                });
    }

    //初始化拨选器
    public void initPicker() {
        dateTimePicker = new DateTimePicker(this, DateTimePicker.DATE_PICKER, true, "选择日期", new
                Date(), 100, new Date());
        dateTimePicker.generatePicker();
    }
}
